'''
Created on Jun 21, 2012

@author: thomas_dao
'''
from app import bill_async
from web import base
from web.base import BaseHandler
from web import urls
from web import util
import json
import logging
from google.appengine.ext import ndb
from webapp2_extras.appengine.auth.models import User
from entity.entity import FriendBill

     
class CreateHandler(BaseHandler):
    @base.user_required
    def post(self):
        pass    

class ReadHandler(BaseHandler):
    def get(self):
        pass
    

class UpdateHandler(BaseHandler):
    @ndb.synctasklet
    @base.user_required
    def post(self):
        reply = self.request.params.get('reply')
        friend_bill_id = self.request.params.get('friend_bill_id')
        friend_bill = FriendBill.get_by_id(int(friend_bill_id))
        friend_bill.reply = reply
        paid = self.request.params.get('paid')
        if paid == "paid":
            friend_bill.paid = True
        elif paid == "unpaid":
            friend_bill.paid = False
        friend_bill.put()
        output = yield util.ndb_to_dict_async(friend_bill, detail=["owner", "bill"])
        self.response.write(json.dumps(output))        
    
    def get(self):
        friend_bill_id = self.request.params.get('friend_bill_id')
        paid = self.request.params.get('paid')
        friend_bill = FriendBill.get_by_id(int(friend_bill_id))
        if paid == "paid":
            friend_bill.paid = True
        elif paid == "unpaid":
            friend_bill.paid = False
        friend_bill.put()
        self.response.write(json.dumps(util.ndb_to_dict(friend_bill)))

class DeleteHandler(BaseHandler):
    @ndb.synctasklet
    @base.user_required
    def post(self):
        friend_bill_id = self.request.params.get('friend_bill_id')
        friend_bill_key = ndb.Key(FriendBill, int(friend_bill_id))
        friend_bill_key.delete()
        
        # Response
        page = yield bill_async.my_requested_bills(util.get_current_user_key())
        self.response.write(json.dumps(page))

    
app = urls.app

def main():
    app.run()

if __name__ == '__main__':
    main()